package cn.wolfcode.luowowo2.memberserver.service.impl;

import cn.wolfcode.luowowo2.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo2.cache.prefix.VerifyCodeKeyPrefix;
import cn.wolfcode.luowowo2.cache.service.IRedisService;
import cn.wolfcode.luowowo2.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo2.cache.service.IVerifyCodeRedisService;
import cn.wolfcode.luowowo2.common.util.AssertUtil;
import cn.wolfcode.luowowo2.common.util.Consts;
import cn.wolfcode.luowowo2.common.util.DisableExeption;
import cn.wolfcode.luowowo2.member.domain.UserInfo;
import cn.wolfcode.luowowo2.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo2.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;

/**
 * Created by Albert on 2019/7/5.
 */
@Service //此处使用Dubbo的service
public class UserInfoServiceImpl implements IUserInfoService{
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Value("${msg.url}")
    private String msgUrl;
    @Value("${msg.key}")
    private String msgKey;


    @Reference
    private IVerifyCodeRedisService verifyCodeRedisService;

    @Override
    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean checkPhone(String phone) {
        return userInfoMapper.checkPhone(phone)>0;
    }

    @Override
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws DisableExeption{
        //检查是否为空
        AssertUtil.hasLength(phone,"电话不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"验证密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");

        //验证是否为手机号
        AssertUtil.isPhoneNumber(phone);

        //判断两次输入密码是否相同
        AssertUtil.isEquals(password,rpassword,"两次密码输入不相同");

        //判断手机是否唯一
        if (checkPhone(phone)) {
            throw new DisableExeption("手机号已经被注册");
        }

        //判断手机验证码是否正确 //待做
        String originCode = verifyCodeRedisService.getVerifyCode(VerifyCodeKeyPrefix.VERIFY_CODE,phone);
        if(!verifyCode.equals(originCode)){
            throw new DisableExeption("验证码错误");
        }

        //进行保存
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setNickname(nickname);
        userInfo.setPassword(password);
        userInfo.setLevel(1);
        userInfo.setState(UserInfo.STATE_NORMAL);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void sendVerifyCode(String phone) throws DisableExeption{
        //已经校验了

        //生成4位验证码
        String code = UUID.randomUUID().toString().substring(0, 4);
        //发送到手机
        StringBuilder sb = new StringBuilder(80);
        sb.append("验证码是").append(code).append("请在").append(Consts.VERIFY_CODE_VAL_TIME).append("分钟内使用");
        //假装已经发送
        System.out.println(sb);

        try {
            verifyCodeRedisService.sendMsg(phone,sb.toString(),msgUrl,msgKey);
        } catch (Exception e) {
            e.printStackTrace();
        }


        //缓存
        //VerifyCodeServiceImpl.setVerifyCode(code)
        verifyCodeRedisService.setVerifyCode(phone,code);


    }

    @Override
    public String userLogin(String username, String password) throws DisableExeption{
        UserInfo userInfo =userInfoMapper.selectByUsernameAndPassord(username,password);
        if (userInfo==null) {
            throw new DisableExeption("用户名或密码错误");
        }
        //在创建token的同时把token加上前缀作为key值,userInfo作为value值存放在redis中
        return createToken(userInfo);
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }

    private String createToken(UserInfo userInfo) {
        String token = UUID.randomUUID().toString().replace("-", "");

        userInfoRedisService.addToken(UserInfoKeyPrefix.USER_INFO_TOKEN,token,userInfo);

        return token;
    }

    /**
     * 发送短信
     * @param phone
     * @param s
     */
    /*private void sendMsg(String phone, String s) throws Exception{
        //指定访问地址
        URL url = new URL(msgUrl);
        //建立连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //设置请求方法
        connection.setRequestMethod("GET");
        //设置请求参数
        StringBuilder sb = new StringBuilder(100);
        sb.append("sign=【创瑞云】")
                .append("&mobile=").append(phone)
                .append("&content=").append("您的本次的验证码是：0086。")
                .append("&appkey=").append(msgKey);
        //默认是false， 设置true表示输出参数
        connection.setDoOutput(true);
        connection.getOutputStream().write(sb.toString().getBytes("UTF-8"));
        //请求连接
        connection.connect();
        //获取响应数据
        String resp = StreamUtils.copyToString(connection.getInputStream(), Charset.forName("UTF-8"));
        System.out.println(resp);
    }*/
    //发送短信的功能已经搬迁到VerifyCodeRedisService中

}
